﻿using Newtonsoft.Json;
using System.Text;


namespace 测试签名01
{ 

    public class Program
    {
        // 接口服务地址
        private static readonly string RestServer = "http://192.168.10.173:11080/ums/service/V1/res/users";
        // 应用标识
        private static readonly string AppKey = "320000000002";
        // 加密算法
        private static readonly string SignMethod = "SHA-256";
        // 身份系统签发给应用对接的密钥
        private static readonly string AppPwd = "ZNn2fdrvSWR+aGN2ORe/CtMfIq4yuJSzFBtVuaqVnUEJ457QB3W7l0T9yslAMr3H";

        public static async Task Main()
        {

            Console.WriteLine("Hello, World!");

            // 生成签名
            string appPwd = "your_app_password";
            string paramUrl = "your_parameters";
            string signature = TokenUtils.GetSignature(appPwd, paramUrl);



            using (var httpClient = new HttpClient())
            {
                // 时间戳
                long ts = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                // 随机数
                string once = GenerateRandomString(32);

                // 接口 header 中的公共参数
                string commonParamUrl = $"appKey={AppKey}&ts={ts}&once={once}&signMethod={SignMethod}";

                // GET 请求示例
                await DemoGetRequest(httpClient, commonParamUrl, ts, once);

                // POST 请求示例
                await DemoPostRequest(httpClient, commonParamUrl, ts, once);
            }
        }

        private static async Task DemoGetRequest(HttpClient httpClient, string commonParamUrl, long ts, string once)
        {
            try
            {
                string getQueryParam = "startTime=2019-06-21T08:00:00.000Z";
                string getFullUrl = $"{RestServer}?{getQueryParam}";

                // 组合所有参数用于签名
                string getAllParamUrl = $"{commonParamUrl}&{getQueryParam}";

                // 生成签名
                string signData = TokenUtils.GetSignature(AppPwd, getAllParamUrl);

                // 设置请求头
                httpClient.DefaultRequestHeaders.Clear();
                httpClient.DefaultRequestHeaders.Add("appKey", AppKey);
                httpClient.DefaultRequestHeaders.Add("ts", ts.ToString());
                httpClient.DefaultRequestHeaders.Add("once", once);
                httpClient.DefaultRequestHeaders.Add("signMethod", SignMethod);
                httpClient.DefaultRequestHeaders.Add("signData", signData);

                // 发送请求
                var response = await httpClient.GetAsync(getFullUrl);
                if (response.IsSuccessStatusCode)
                {
                    string result = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"GET Response: {result}");
                }
            }
            catch (Exception ex)
            { 
                Console.WriteLine($"GET请求失败: {ex.Message}");
            }
        }

        private static async Task DemoPostRequest(HttpClient httpClient, string commonParamUrl, long ts, string once)
        {
            try
            {
                string id = "aa03a5c692cf480b87887e0ff8cfe566";
                string putQueryParam = $"ID={id}";
                string putFullUrl = $"{RestServer}/{id}";

                // 准备请求体数据
                var dataMap = new Dictionary<string, object>
            {
                { "idcardTypeCode", "01" },
                 { "idcardNum", "32031111111111111" }
            };
                string bodyParam = JsonConvert.SerializeObject(dataMap);

                // 组合所有参数用于签名
                string postAllParamUrl = $"{commonParamUrl}&{putQueryParam}&bodyData={bodyParam}";

                // 生成签名
                string signData = TokenUtils.GetSignature(AppPwd, postAllParamUrl);

                // 设置请求头
                httpClient.DefaultRequestHeaders.Clear();
                httpClient.DefaultRequestHeaders.Add("appKey", AppKey);
                httpClient.DefaultRequestHeaders.Add("ts", ts.ToString());
                httpClient.DefaultRequestHeaders.Add("once", once);
                httpClient.DefaultRequestHeaders.Add("signMethod", SignMethod);
                httpClient.DefaultRequestHeaders.Add("signData", signData);

                // 准备请求内容
                var content = new StringContent(bodyParam, Encoding.UTF8, "application/json");

                // 发送请求
                var response = await httpClient.PostAsync(putFullUrl, content);
                if (response.IsSuccessStatusCode)
                {
                    string result = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"PUT Response: {result}");
                }
            }
            catch (Exception ex)
            { 
                Console.WriteLine($"PUT请求失败: {ex.Message}");
            }
        }

        private static string GenerateRandomString(int length)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            var random = new Random();
            var result = new StringBuilder(length);
            for (int i = 0; i < length; i++)
            {
                result.Append(chars[random.Next(chars.Length)]);
            }
            return result.ToString();
        }
    }
}
